<template>
  <div class="form-main">
    <div class="form-tit" v-if="isTemp">
      <el-form
        :inline="true"
        :model="formdata"
        class="ky-form-inline ky-form-inline-sm">
        <el-form-item label="模板名称：">
          <el-input v-model="formdata.recordCode" placeholder="请输入" style="width: 220px;"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="form-grid">
      <!-- <div class="fg-tit"><div class="txt">预约渠道管理</div></div> -->
      <div class="fg-main">
        <!-- label-position="top" -->
        <el-form
          :inline="true"
          :model="formdata"
          class="ky-form-inline ky-form-inline-sm ruleTemp-channel-form">
          <template v-if="isCombineSelectBox">
            <el-form-item label="预约来源">
              <el-select v-model="channel.newAll.value" placeholder="请选择" multiple clearable>
                <el-option
                  v-for="item in channel.newAll.options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          <template v-else-if="isUseNewSelectBox">
            <el-form-item label="预约来源">
              <el-select v-model="channel.YYLY.value" placeholder="请选择" multiple clearable>
                <el-option
                  v-for="item in channel.YYLY.options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="外院预约">
              <el-select v-model="channel.WYYY.value" placeholder="请选择" multiple clearable>
                <el-option
                  v-for="item in channel.WYYY.options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="临床预约">
              <el-select v-model="channel.LCYY.value" placeholder="请选择" multiple clearable>
                <el-option
                  v-for="item in channel.LCYY.options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="转诊预约">
              <el-select v-model="channel.VIP.value" placeholder="请选择" multiple clearable>
                <el-option
                  v-for="item in channel.VIP.options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>

    <div class="form-grid">
      <div class="fg-tit">
        <div class="txt">过滤条件</div>
        <div class="flr-add" @click="addCondition"><i class="el-icon-circle-plus-outline"></i> 添加条件</div>
      </div>
      <div class="fg-main flr-main">
        <div
          class="rule-item"
          v-for="(item, index) in formdata.appointmentFilters"
          :key="index"
        >
          <el-select
            style="width: 154px"
            size="small"
            v-model="item.parametersType"
            placeholder="请选择过滤条件"
            clearable
            @change="changeCondition(item, index)"
          >
            <el-option
              v-for="_item in ruleConditionOptionsFlr"
              :key="_item.dicEname"
              :label="_item.dicName"
              :value="_item.dicEname"
            ></el-option>
          </el-select>
          <el-input-number
            style="width: 175px"
            size="small"
            v-model="item.parametersValues"
            v-if="item.conditionControl === '1'"
          ></el-input-number>
          <el-input
            v-else-if="item.conditionControl === '2'"
            style="width: 175px"
            class="inline-input"
            size="small"
            v-model="item.parametersValues"
            :placeholder="`请输入${item.parametersType?placeholderKey[index]||'':''}`"
            clearable
          ></el-input>
          <el-select
            v-else-if="item.conditionControl === '3' || item.conditionControl === '5'"
            style="width: 175px"
            size="small"
            v-model="item.parametersValues"
            :multiple="item.conditionControl === '3' || item.conditionControl === '5'"
            :placeholder="`请选择${item.parametersType?placeholderKey[index]||'':''}`"
            clearable
          >
            <el-option
              v-for="(
                firitem, _index
              ) in item.conditionSelectValueOptions"
              :key="_index"
              :label="firitem"
              :value="firitem"
            ></el-option>
          </el-select>
          <!-- <el-select
            v-else-if="item.conditionControl === '5'"
            style="width: 175px"
            size="small"
            multiple
            v-model="item.parametersValues"
            :placeholder="`请选择${item.parametersType?placeholderKey[index]||'':''}`"
            clearable
          >
            <el-option
              v-for="(
                secitem, _index
              ) in item.conditionSelectValueOptions"
              :key="_index"
              :label="secitem"
              :value="secitem"
            ></el-option>
          </el-select> -->
          <el-date-picker
            v-else-if="item.conditionControl === '4'"
            size="small"
            style="width: 175px"
            v-model="item.parametersValues"
            type="date"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <el-input v-else style="width:175px" class="inline-input" size="small" v-model="item.parametersValues" :placeholder="`请输入${item.parametersType?placeholderKey[index]||'':''}`" clearable></el-input>
          <i
            class="el-icon-error"
            @click="deleteCondition(index)"
          ></i>
          <!-- v-if="formdata.appointmentFilters.length != 1" -->
        </div>
      </div>
    </div>

    <div class="form-grid" v-loading="treeLoading">
      <el-row :gutter="10">
        <el-col :span="parametersTypeByPart === $store.state.user.parametersTypeByPartKey1?11:24">
          <div class="fg-tit flex flex-row justify-between">
            <div class="txt">检查部位<span v-if="bigpartDataZC.length" class="tit_tips">（{{bigpartChecked.length}}/{{bigpartDataZC.length}}）</span></div>
            <div class="flex flex-row">
              <div>
                <el-checkbox v-model="isFilterBigPart" @change="changeIsFilterBigPart">同步设备过滤</el-checkbox>
              </div>
              <div class="mar-l-10">
                <el-checkbox :indeterminate="bigpartIsIndeterminate" v-model="bigpartCheckAll" @change="handleCheckAllChangeBigpart">全选</el-checkbox>
              </div>
            </div>
          </div>
          <div class="fg-main table-main" v-loading="treeBigpartloading">
            <el-form
              ref="formdata"
              :inline="true"
              :model="formdata"
              @submit.native.prevent
              class="ky-form-inline ky-form-inline-sm">
              <el-form-item>
                <el-input prefix-icon="el-icon-search" v-model="filterTextBigpart" size="small" placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item class="inline-block checkbox_fitem">
                <div class="checkbox_box">
                  <div v-if="bigpartData.length>0">
                    <el-checkbox-group v-model="bigpartChecked" @change="handleCheckChangeBigpart">
                      <virtualList
                        ref="virtualList1"
                        style="height: 470px; overflow-y: auto;"
                        :data-key="'id'"
                        :data-sources="bigpartData"
                        :data-component="itemComponent"/>
                      <!-- <el-checkbox v-for="(item,index) in bigpartData" :label="item" :key="index" :title="item">{{item}}</el-checkbox> -->
                    </el-checkbox-group>
                  </div>
                  <div v-if="bigpartData.length===0" class="ky-listnone">暂无数据！</div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="13" v-if="parametersTypeByPart === $store.state.user.parametersTypeByPartKey1">
          <div class="fg-tit flex flex-row justify-between">
            <div class="txt">检查项目<span v-if="smallpartDataZC.length" class="tit_tips">（{{smallpartChecked.length}}/{{smallpartDataZC.length}}）</span></div>
            <div class="flex flex-row">
              <div>
                <el-checkbox v-model="isFilterSmallPart" @change="changeIsFilterSmallPart">同步设备过滤</el-checkbox>
              </div>
              <div class="mar-l-10">
                <el-checkbox :indeterminate="smallpartIsIndeterminate" v-model="smallpartCheckAll" @change="handleCheckAllChangeSmallpart">全选</el-checkbox>
              </div>
            </div>
          </div>
          <div class="fg-main table-main" v-loading="treeSmallpartloading">
            <el-form
              ref="formdata"
              :inline="true"
              :model="formdata"
              @submit.native.prevent
              class="ky-form-inline ky-form-inline-sm">
              <el-form-item>
                <el-input prefix-icon="el-icon-search" v-model="filterTextSmallpart" size="small" placeholder="请输入内容"></el-input>
              </el-form-item>
              <el-form-item class="inline-block checkbox_fitem">
                <div class="checkbox_box">
                  <div v-if="smallpartData.length>0">
                    <el-checkbox-group v-model="smallpartChecked" @change="handleCheckChangeSmallpart">
                      <virtualList
                        ref="virtualList2"
                        style="height: 470px; overflow-y: auto;"
                        :data-key="'id'"
                        :data-sources="smallpartData"
                        :data-component="itemComponent"/>
                      <!-- <el-checkbox v-for="(item,index) in smallpartData" :label="item" :key="index" :title="item">{{item}}</el-checkbox> -->
                    </el-checkbox-group>
                  </div>
                  <div v-if="smallpartData.length===0" class="ky-listnone">暂无数据！</div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import { setLocalStorage } from '@/utils/localStorage'
import {
  getItemDicList
} from '@/api/api'
import { getDefaultRoom } from '@/utils/auth'
// import { getRoomTagCurr } from '@/utils/utils'
import { sysAppId } from '@/settings.js'
import { depSalt, getHisCheckroomgetSmallpartlistRoom, getBigPartListRoom } from '@/api/room'
import { Options } from '@/utils/constant'
import { mapGetters } from 'vuex'
import getDicOptions from '@/mixin/getDicOptions'
import virtualList from 'vue-virtual-scroll-list'
const channelSplitKey = '、'
let parametersTypeByPart1 = 'bigpart'
let parametersTypeByPart2 = 'dengjipart'
// 定义检查部位选项模板组件
const checkboxItem = {
  name: 'ItemComponent',
  props: {
    index: {
      type: Number
    },
    source: {
      // {id: '1', value: 'abc'}
      type: Object,
      default() {
        return {}
      }
    }
  },
  template: `<el-checkbox :label="source.value" :title="source.value">{{source.value}}</el-checkbox>`
}
export default {
  components: { virtualList },
  mixins: [getDicOptions],
  props: {
    hospitalCode: {
      type: String,
      default: ''
    },
    dep: {
      type: String,
      default: ''
    },
    isTemp: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      smallPartNodes: '',
      parametersValuesSplit: this.$store.state.user.parametersValuesSplit,
      parametersTypeByPart: parametersTypeByPart1, // 'dengjipart'
      parametersTypeByPartDep: '',
      itemComponent: checkboxItem,
      getBigPartFlag: false, // 获取大部位锁
      modality: '',
      options: Options,
      formdata: {
        recordCode: '', // 模板名称
        appointmentFilters: []
      },
      ruleConditionOptionsFlr: [], // 过滤条件
      ruleConditionOptions: [], // 规则数据字典
      checkedPartNodes: [], // 选中的检查部位
      // 预约渠道
      channel: {
        WYYY: {
          value: [],
          label: '外院预约',
          isShow: true,
          options: Options.channelOptions.WYYY
        },
        LCYY: {
          value: [],
          label: '临床预约',
          isShow: true,
          options: Options.channelOptions.LCYY
        },
        VIP: {
          value: [],
          label: '转诊预约',
          isShow: true,
          options: Options.channelOptions.VIP
        },
        newAll: {
          value: [],
          label: '预约来源',
          isShow: true,
          options: Options.channelOptions.newAll
        },
        YYLY: {
          value: [],
          label: '预约来源',
          isShow: true,
          options: Options.channelOptions.YYLY
        }
      },
      // 检查部位
      treeLoading: false,
      treeBigpartloading: false,
      treeSmallpartloading: false,
      bigpartCheckAll: false,
      bigpartIsIndeterminate: false,
      bigpartChecked: [],
      bigpartDataZC: [],
      bigpartData: [],
      filterTextBigpart: '',
      smallpartCheckAll: false,
      smallpartIsIndeterminate: false,
      smallpartChecked: [],
      smallpartDataZC: [],
      smallpartData: [],
      filterTextSmallpart: '',
      isFilterSmallPart: false,
      isFilterBigPart: false,
      placeholderKey: [] // 记录切换控件显示的默认提醒
    }
  },
  watch: {
    filterTextBigpart(val) {
      this.filterBigpart(val)
    },
    filterTextSmallpart(val) {
      this.filterSmallpart(val)
    },
    hospitalCode(val) {
      if (this.dep && val && !this.getBigPartFlag) {
        this.bigpartDataZC = []
        this.smallpartDataZC = []
        this.getBigPartGettreeList()
      }
    },
    dep(val) {
      this.getParameterDep()
      if (this.hospitalCode && val && !this.getBigPartFlag) {
        this.bigpartDataZC = []
        this.smallpartDataZC = []
        this.getBigPartGettreeList()
      }
    }
  },
  computed: {
    ...mapGetters(['appSetting', 'appointmentTypeOptions']),
    appConfig() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig
    },
    isCombineSelectBox() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isCombineSelectBox
    },
    isUseNewSelectBox() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isUseNewSelectBox
    }
  },
  // beforeCreate() {
  //   this.bigpartData = []
  //   this.bigpartDataZC = []
  //   this.smallpartData = []
  //   this.smallpartDataZC = []
  // },
  beforeDestroy() {
    console.log('ruleTemplate beforeDestroy')
    this.setTimeout01 && clearTimeout(this.setTimeout01)
    // this.timeout01 && clearTimeout(this.timeout01)
  },
  created() {
    parametersTypeByPart1 = this.$store.state.user.parametersTypeByPartKey1 // BIGPART
    parametersTypeByPart2 = this.$store.state.user.parametersTypeByPartKey2 // dengjipart
    // console.log('parametersTypeByPart1', parametersTypeByPart1)
    // console.log('parametersTypeByPart2', parametersTypeByPart2)
    this.parametersTypeByPart = parametersTypeByPart1 // BIGPART
    // console.log('this.parametersTypeByPart==init', this.parametersTypeByPart) // BIGPART
    // console.log('$store.state.user.parametersTypeByPartKey1==', this.$store.state.user.parametersTypeByPartKey1)
    // console.log('$store.state.user.parametersTypeByPartKey2', this.$store.state.user.parametersTypeByPartKey2) // dengjipart
    this.getParameterDep()
    this.getTypeOptions()
  },
  methods: {
    changeIsFilterBigPart(e) {
      this.getBigPart(e)
    },
    changeIsFilterSmallPart(e) {
      this.getAllSmallpart(e)
    },
    async getTypeOptions() {
      // 如果在配置文件配置，则不在数据字段获取
      if (window.g.APPOINT_TYPE_OPTIONS) {
        this.channel.YYLY.options = window.g.APPOINT_TYPE_OPTIONS
        // if (window.g.APPOINT_TYPE_OPTIONS.length) {
        //   let appointList = window.g.APPOINT_TYPE_OPTIONS
        //   // this.appoint_type = appointList[0]
        // }
        return
      }
      if (this.appointmentTypeOptions.length === 0) {
        let params = { HospitalCode: this.hospitalCode, type: '预约来源' }
        await this.$store.dispatch('settings/set_appointTypeOptions', params)
        this.channel.YYLY.options = this.appointmentTypeOptions
      }
    },
    getParameterDep() {
      let _dep = ''
      if (this.dep) { // this.dep=>1 SALT-DEP-CT
        _dep = this.dep.replace(depSalt, '') // depSalt = 'SALT-DEP-'
      }
      // _dep = CT
      this.parametersTypeByPart = parametersTypeByPart1
      const _deps = this.$store.state.user.depSettings
      // console.log('_deps', JSON.stringify(_deps))
      // _deps
      // [{"dep":"CT","parametersTypeByPart":"dengjipart"},{"dep":"MRI","parametersTypeByPart":"bigpart"},{"dep":"XRAY","parametersTypeByPart":"bigpart"}]
      if (_dep && _deps && _deps.length > 0) {
        _deps.forEach(item => {
          if (item.parametersTypeByPart === parametersTypeByPart2 && item.dep === _dep) {
            this.parametersTypeByPart = parametersTypeByPart2 // 'BIGPART' // parametersTypeByPart2
            setLocalStorage('parametersTypeByPart', this.parametersTypeByPart)
            // console.log('this.parametersTypeByPart==result', this.parametersTypeByPart) // BIGPART
            // 当this.parametersTypeByPart == dengjipart 将大部位值替换成dengjipart且不判断小部位
          }
        })
      }
      // // console.log('_dep_dep_dep_dep', _dep)
      // // console.log('parametersTypeByPart', this.parametersTypeByPart)
    },
    async init(data) {
      const deptRoom = getDefaultRoom()
      console.log('init=>deptRoom', deptRoom)
      // console.log('==deptRoom=>', deptRoom[3].split('-')[2])
      // const Modality = deptRoom.split('#')[1]
      this.modality = deptRoom.length && deptRoom[3].split('-')[2]
      console.log('==this.modality=>', this.modality)
      console.log('ruleTempLate=>init=>data', data)
      await this.getRuleItemDicList()
      // this.getAllSmallpart()
      if (this.hospitalCode && this.dep && this.bigpartDataZC.length === 0 && !this.getBigPartFlag) {
        await this.getBigPartGettreeList()
      }
      console.log('=====this.resetInit======')
      console.log('tohere')
      this.resetInit(data)
    },
    resetInit(data) { // data是当个号源
      console.log('ruleTemplate=>初始化数据resetInit_data', data)
      this.channel['WYYY'].value = []
      this.channel['LCYY'].value = []
      this.channel['VIP'].value = []
      this.channel['newAll'].value = []
      this.channel['YYLY'].value = []
      const fileterChannel = ['WYYY', 'LCYY', 'VIP', 'newAll', 'YYLY']
      console.log('resetInit=>this.ruleConditionOptions111', this.ruleConditionOptions)
      this.ruleConditionOptions = this.ruleConditionOptions.filter(item => fileterChannel.indexOf(item.dicEname) == -1)
      this.ruleConditionOptions.forEach(item => {
        console.log('item.dicEname', item.dicEname)
      })
      console.log('resetInit=>this.ruleConditionOptions222', this.ruleConditionOptions)
      // this.formdata.appointmentFilters = data && data.appointmentFilters ? JSON.parse(JSON.stringify(data.appointmentFilters)) : []
      this.formdata.appointmentFilters = data && data.appointmentFilters ? JSON.parse(JSON.stringify(data.appointmentFilters.filter(ap => this.ruleConditionOptions.find(rc => rc.dicEname === ap.parametersType)))) : []
      // resFlr.appointmentFilters = resFlr.appointmentFilters.filter(ap => this.ruleConditionOptions.find(rc => rc.dicEname === ap.parametersType))
      console.log('打印过滤条件this.formdata.appointmentFilters', this.formdata.appointmentFilters)
      console.log('=====================')
      console.log('this.channel', this.channel)
      // this.formdata.recordCode = data ? this.isTemp ? data.recordCode : data.remark1 : ''
      if (this.isTemp && data && !data.templateSelected) {
        this.formdata.recordCode = data ? this.isTemp ? data.recordCode : data.remark1 : ''
      }
      this.bigpartChecked = []
      // console.log('待查看bigpartChecked', this.bigpartChecked)
      this.bigpartCheckAll = false
      this.bigpartIsIndeterminate = false
      this.smallpartChecked = []
      this.smallpartCheckAll = false
      this.smallpartIsIndeterminate = false
      this.calSetRule(data)
      this.$nextTick(() => {
        this.getAllSmallpart()
      }, 300)
    },
    getRuleData() {
      // console.log('+++++++++++弹窗中的保存按钮被点击，触发保存事件saveSend,然后调用getRuleData函数++++++++++++++')
      // console.log('======into getRuleData======print this.formdata', this.formdata)
      return new Promise(async resolve => {
        const resFlr = JSON.parse(JSON.stringify(this.formdata))
        console.log('待查看resFlr=>formdata', resFlr)
        // console.log('初始resFlr.appointmentFilters检查部位', resFlr.appointmentFilters)
        // 判断数据格式
        for (let i = 0; i < resFlr.appointmentFilters.length; i++) {
          // console.log('待查看resFlr.appointmentFilters[i]', resFlr.appointmentFilters[i])
          // 如果只有一组空数据，直接跳过
          if (!resFlr.appointmentFilters[i].parametersType && !resFlr.appointmentFilters[i].parametersValues) {
            resFlr.appointmentFilters.splice(i, 1)
            continue
          }
          if (resFlr.appointmentFilters[i].parametersValues && typeof resFlr.appointmentFilters[i].parametersValues === 'object') {
            resFlr.appointmentFilters[i].parametersValues = resFlr.appointmentFilters[i].parametersValues.join(channelSplitKey)
          } else if (typeof resFlr.appointmentFilters[i].parametersValues === 'number') {
            // 直接改格式，改了以后 下面会重新变回原来的格式
            if (resFlr.appointmentFilters[i].parametersValues < 0) {
              this.$message.warning(`${resFlr.appointmentFilters[i].parametersName} 不能小于0`)
              return false
            }
            let copyData = {
              parametersName: resFlr.appointmentFilters[i].parametersName,
              parametersType: resFlr.appointmentFilters[i].parametersType,
              parametersValues: resFlr.appointmentFilters[i].parametersValues.toString()
            }
            delete resFlr.appointmentFilters[i]
            resFlr.appointmentFilters[i] = copyData
          }
          if (!resFlr.appointmentFilters[i].parametersValues && resFlr.appointmentFilters[i].parametersType) {
            this.$message.warning('请完整输入参数列表数据')
            return
          }
        }

        const _bigpart = [...this.bigpartChecked]
        // console.log('待查看_bigpart=======大部位>', _bigpart)
        if (_bigpart && _bigpart.length > 0) {
          // console.log('待查看this.parametersTypeByPart==>重要信息', this.parametersTypeByPart)
          const _bigpartObj = {
            parametersType: this.parametersTypeByPart,
            parametersValues: _bigpart.join(this.parametersValuesSplit),
            parametersName: '检查部位'
          }
          // console.log('待查看_bigpartObj', _bigpartObj)
          resFlr.appointmentFilters.push(_bigpartObj)
        }
        // console.log('带查看得到新的resFlr.appointmentFilters====>', resFlr.appointmentFilters)
        const _smallpart = [...this.smallpartChecked]
        // console.log('待查看_smallpart=======小部位>', _smallpart)
        // 这里待查看哦
        // console.log('待查看this.parametersTypeByPart', this.parametersTypeByPart)
        // console.log('待查看parametersTypeByPart2', parametersTypeByPart2)
        if (_smallpart && _smallpart.length > 0 && this.parametersTypeByPart !== parametersTypeByPart2) {
          const __smallpartObj = {
            parametersType: parametersTypeByPart2,
            parametersValues: _smallpart.join(this.parametersValuesSplit),
            parametersName: '检查项目'
          }
          // console.log('待查看__smallpartObj', __smallpartObj)
          resFlr.appointmentFilters.push(__smallpartObj)
        }
        // console.log('带查看得到新的resFlr.appointmentFilters====>', resFlr.appointmentFilters)
        // 预约渠道获取
        console.log('预约渠道获取', this.channel)
        // 判断是否开启预约来源改版开关
        if (this.isCombineSelectBox) {
          for (let k in this.channel) {
            if (k == 'newAll') {
              let filterValue = this.channel[k].value
              if (filterValue.length > 0) {
                console.log('filterValue', filterValue)
                if (filterValue.indexOf('互联网预约') > -1) {
                  const _appoFlrObj = {
                    parametersName: '外院预约',
                    parametersType: 'WYYY',
                    parametersValues: '互联网预约'
                  }
                  resFlr.appointmentFilters.push(_appoFlrObj)
                } else {
                  const _appoFlrObj = {
                    parametersName: '外院预约',
                    parametersType: 'WYYY',
                    parametersValues: '非互联网预约'
                  }
                  resFlr.appointmentFilters.push(_appoFlrObj)
                }
                let lcyyArr = []
                if (filterValue.indexOf('临床预约') > -1) {
                  lcyyArr.push('临床预约')
                } else {
                  lcyyArr.push('非临床预约')
                }
                if (filterValue.indexOf('联合预约') > -1) {
                  lcyyArr.push('联合预约')
                }
                const _appoFlrObj = {
                  parametersName: '临床预约',
                  parametersType: 'LCYY',
                  parametersValues: lcyyArr.join('、')
                }
                resFlr.appointmentFilters.push(_appoFlrObj)
                if (filterValue.indexOf('转诊预约') > -1) {
                  const _appoFlrObj = {
                    parametersName: '转诊预约',
                    parametersType: 'VIP',
                    parametersValues: '转诊预约'
                  }
                  resFlr.appointmentFilters.push(_appoFlrObj)
                } else {
                  const _appoFlrObj = {
                    parametersName: '转诊预约',
                    parametersType: 'VIP',
                    parametersValues: '非转诊预约'
                  }
                  resFlr.appointmentFilters.push(_appoFlrObj)
                }
                // filterValue.forEach(item => {
                //   if (item == '互联网预约') {
                //     const _appoFlrObj = {
                //       parametersName: '外院预约',
                //       parametersType: 'WYYY',
                //       parametersValues: item
                //     }
                //     resFlr.appointmentFilters.push(_appoFlrObj)
                //   }
                // })
              } else {
                let _appoFlrObj = {
                  parametersName: '外院预约',
                  parametersType: 'WYYY',
                  parametersValues: '非互联网预约'
                }
                resFlr.appointmentFilters.push(_appoFlrObj)
                _appoFlrObj = {
                  parametersName: '临床预约',
                  parametersType: 'LCYY',
                  parametersValues: '非临床预约'
                }
                resFlr.appointmentFilters.push(_appoFlrObj)
                _appoFlrObj = {
                  parametersName: '转诊预约',
                  parametersType: 'VIP',
                  parametersValues: '非转诊预约'
                }
                resFlr.appointmentFilters.push(_appoFlrObj)
              }
            }
            // if (this.channel[k].value.length > 0) {
            //   const _appoFlrObj = {
            //     parametersType: k,
            //     parametersValues: this.channel[k].value.join(channelSplitKey),
            //     parametersName: this.channel[k].label
            //   }
            //   resFlr.appointmentFilters.push(_appoFlrObj)
            // }
          }
        } else if (this.isUseNewSelectBox) {
          console.log('=====================')
          console.log('this.channel', this.channel)
          for (let k in this.channel) {
            if (k == 'YYLY') {
              if (this.channel[k].value.length > 0) {
                const _appoFlrObj = {
                  parametersType: k,
                  parametersValues: this.channel[k].value.join(channelSplitKey),
                  parametersName: this.channel[k].label
                }
                console.log('_appoFlrObj', _appoFlrObj)
                resFlr.appointmentFilters.push(_appoFlrObj)
              }
            }
          }
          console.log('resFlr=>这里处理了YYLY.value', resFlr)
          console.log('resFlr=>这里处理了YYLY.value', JSON.stringify(resFlr))
        } else {
          for (let k in this.channel) {
            if (this.channel[k].value.length > 0) {
              const _appoFlrObj = {
                parametersType: k,
                parametersValues: this.channel[k].value.join(channelSplitKey),
                parametersName: this.channel[k].label
              }
              resFlr.appointmentFilters.push(_appoFlrObj)
            }
          }
        }
        // 过滤号源时段限制条件限制中没有的数据
        console.log('待查看，整合后的resFlr.appointmentFilters====>', resFlr.appointmentFilters)
        // console.log('待查看，循环之前this.ruleConditionOptions', this.ruleConditionOptions)
        for (let i = 0; i < resFlr.appointmentFilters.length; i++) {
          if (resFlr.appointmentFilters[i].parametersType === 'BIGPART' || resFlr.appointmentFilters[i].parametersType === 'bigpart') {
            for (let j = 0; j < this.ruleConditionOptions.length; j++) {
              if (this.ruleConditionOptions[j].dicEname === 'BIGPART' || this.ruleConditionOptions[j].dicEname === 'bigpart') {
                this.ruleConditionOptions[j].dicEname = resFlr.appointmentFilters[i].parametersType
                this.ruleConditionOptions[j].dicName = resFlr.appointmentFilters[i].parametersName
              }
            }
          }
        }
        console.log('待查看，循环之后this.ruleConditionOptions=>', this.ruleConditionOptions)
        this.ruleConditionOptions.forEach(item => {
          console.log('dicName', item.dicName)
        })
        console.log('待查看，整合后=>过滤前的resFlr.appointmentFilters--result', resFlr.appointmentFilters)
        // resFlr.appointmentFilters = resFlr.appointmentFilters.filter(ap => this.ruleConditionOptions.find(rc => rc.dicEname === ap.parametersType))
        console.log('待查看，整合后过滤后的resFlr.appointmentFilters--result', resFlr.appointmentFilters)
        // resFlr.appointmentFilters.push({ parametersType: 'VIPNUM', parametersValues: '1', parametersName: 'VIP数量' })
        // resFlr.appointmentFilters.push({ parametersType: 'VVIPNU', parametersValues: '1', parametersName: 'VVVIP数量' })
        // 判断是否为快速选择模板参数模板数据
        resFlr.recordCode = this.isTemp ? this.formdata.recordCode : resFlr.recordCode
        console.log('resFlr', resFlr)
        resolve(JSON.stringify(resFlr))
      })
    },
    calSetRule(data) {
      console.log('calSetRule=>data', data)
      console.log('this.formdata.appointmentFilters', this.formdata.appointmentFilters)
      // if (!this.formdata.appointmentFilters) return
      let valueResult = [] // valueResult是给newAll用的
      let appoFlr = []
      console.log('data.appointmentFilters', JSON.stringify(data.appointmentFilters))
      console.log('this.ruleConditionOptions', this.ruleConditionOptions)
      this.ruleConditionOptions.forEach(item => {
        console.log('dicName', item.dicName)
      })
      if (data && data.appointmentFilters) {
        const filterResult = data.appointmentFilters.filter(ap => this.ruleConditionOptions.find(rc => rc.dicEname === ap.parametersType))
        console.log('filterResult', filterResult)
        appoFlr = JSON.parse(JSON.stringify(filterResult))
      } else {
        appoFlr = []
      }
      this.formdata.appointmentFilters = []
      console.log('calSetRule=>appoFlr', appoFlr)
      const appoFlrChannel = data && data.appointmentFilters && data.appointmentFilters.length && JSON.parse(JSON.stringify(data.appointmentFilters)) || []
      if (appoFlr.length === 0 || appoFlrChannel.length === 0) {
        this.addCondition()
      }
      // 过滤fromdata里的数据
      for (let index = 0; index < appoFlr.length; index++) {
        let flrObj = appoFlr[index]
        console.log('appoFlr=>flrObj-filter', flrObj)
        if (flrObj.parametersType === this.parametersTypeByPart) {
          // 检查部位
          const _bigpart = flrObj.parametersValues.split(this.parametersValuesSplit)
          this.bigpartChecked = _bigpart.filter(item => {
            return item
          })
          // console.log('this.bigpartChecked', this.bigpartChecked) // ['上肢', '下肢']
          this.handleCheckChangeBigpart(this.bigpartChecked)
          continue
        }
        console.log('flrObj.parametersType', flrObj.parametersType)
        console.log('this.parametersTypeByPart', this.parametersTypeByPart)
        console.log('parametersTypeByPart2', parametersTypeByPart2)
        if (flrObj.parametersType === parametersTypeByPart2 && this.parametersTypeByPart !== parametersTypeByPart2) {
          // 检查项目
          const _smallpart = flrObj.parametersValues.split(this.parametersValuesSplit)
          console.log('_smallpart', _smallpart)
          this.smallpartChecked = _smallpart.filter(item => {
            return item
          })
          console.log('calSetRule=>this.smallpartChecked', this.smallpartChecked)
          // console.log('this.smallpartChecked', this.smallpartChecked)
          this.handleCheckChangeSmallpart(this.smallpartChecked)
          continue
        }
        // resFlr.appointmentFilters = resFlr.appointmentFilters.filter(ap => this.ruleConditionOptions.find(rc => rc.dicEname === ap.parametersType))
        let filters = {
          parametersType: flrObj.parametersType,
          parametersValues: flrObj.parametersValues,
          parametersName: flrObj.remark1,
          conditionControl: '',
          conditionSelectValueOptions: []
        }
        // this.formdata.appointmentFilters.push(filters)
        // console.log('this.formdata.appointmentFilters', this.formdata.appointmentFilters)
        // 过滤条件中过滤掉检查部位的显示（为了修复过滤条件的历史BUG而添加）由于加了之后就不适配温州市中心医院的bigpart转dengjipart的需求了，所以不能这么写
        // // console.log('===this.formdata.appointmentFilters===push===', filters)
        // if (flrObj.parametersType.toLowerCase() !== 'bigpart') {
        //   this.formdata.appointmentFilters.push(filters)
        // }
        // 过滤条件中过滤掉检查部位的显示（为了修复过滤条件的历史BUG而添加）
        // this.formdata.appointmentFilters.push(filters)
        if (flrObj.parametersName !== '检查部位') {
          this.formdata.appointmentFilters.push(filters)
        }
        const appoFlrLen = this.formdata.appointmentFilters.length
        // console.log('appoFlrLen', appoFlrLen)
        // console.log('this.formdata.appointmentFilters[appoFlrLen - 1]', this.formdata.appointmentFilters[appoFlrLen - 1])
        this.$nextTick(() => {
          this.changeCondition(this.formdata.appointmentFilters[appoFlrLen - 1], appoFlrLen - 1, 'init')
        }, 500)
      }
      console.log('========================this.formdata.appointmentFilters=============================')
      console.log('this.formdata.appointmentFilters', this.formdata.appointmentFilters)
      // 处理预约来源的数据
      for (let index = 0; index < appoFlrChannel.length; index++) {
        let flrObj = appoFlrChannel[index]
        console.log('appoFlrChannel=》flrObj', flrObj)
        if (flrObj.parametersType === 'WYYY' || flrObj.parametersType === 'LCYY' || flrObj.parametersType === 'VIP') {
          // 外院预约、临床预约、转诊预约
          this.channel[flrObj.parametersType].value = flrObj.parametersValues ? flrObj.parametersValues.split(channelSplitKey) : []
          if (this.isCombineSelectBox) {
            let value = flrObj.parametersValues ? flrObj.parametersValues.split(channelSplitKey) : []
            if (value && value.length) {
              if (flrObj.parametersType == 'WYYY' || flrObj.parametersName == '外院预约') {
                value.forEach(item => {
                  if (item == '互联网预约') {
                    valueResult.push('互联网预约')
                  }
                  if (item == '非互联网预约') {
                    if (valueResult.indexOf('非互联网预约') > -1) {
                      valueResult.splice(valueResult.indexOf('非互联网预约'), 1)
                    }
                    if (valueResult.indexOf('互联网预约') > -1) {
                      valueResult.splice(valueResult.indexOf('互联网预约'), 1)
                    }
                  }
                })
              }
              if (flrObj.parametersType == 'LCYY' || flrObj.parametersName == '临床预约') {
                value.forEach(item => {
                  if (item == '临床预约') {
                    valueResult.push('临床预约')
                  }
                  if (item == '非临床预约') {
                    if (valueResult.indexOf('非临床预约') > -1) {
                      valueResult.splice(valueResult.indexOf('非临床预约'), 1)
                    }
                    if (valueResult.indexOf('临床预约') > -1) {
                      valueResult.splice(valueResult.indexOf('临床预约'), 1)
                    }
                  }
                  if (item == '联合预约') {
                    valueResult.push('联合预约')
                  }
                })
                // 临床预约来源数据内临床预约和非临床预约为空的情况，临床预约选项不勾选
                if (value.indexOf('临床预约') < 0 && value.indexOf('非临床预约') < 0) {
                  if (valueResult.indexOf('非临床预约') > -1) {
                    valueResult.splice(valueResult.indexOf('非临床预约'), 1)
                  }
                  if (valueResult.indexOf('临床预约') > -1) {
                    valueResult.splice(valueResult.indexOf('临床预约'), 1)
                  }
                }
                // 临床预约数据内联合预约为空的情况下，联合预约不勾选
                if (value.indexOf('联合预约') < 0) {
                  if (valueResult.indexOf('联合预约') > -1) {
                    valueResult.splice(valueResult.indexOf('联合预约'), 1)
                  }
                }
              }
              if (flrObj.parametersType == 'VIP' || flrObj.parametersName == '转诊预约') {
                value.forEach(item => {
                  if (item == '转诊预约') {
                    valueResult.push('转诊预约')
                  }
                  if (item == '非转诊预约') {
                    if (valueResult.indexOf('非转诊预约') > -1) {
                      valueResult.splice(valueResult.indexOf('非转诊预约'), 1)
                    }
                    if (valueResult.indexOf('转诊预约') > -1) {
                      valueResult.splice(valueResult.indexOf('转诊预约'), 1)
                    }
                  }
                })
              }
              // this.channel['newAll'].value = valueResult
            } else {
              // 外院预约来源为空的情况，互联网预约选项不勾选，为了保险起见(老数据问题)，非互联网预约也给过滤掉
              if (flrObj.parametersType == 'WYYY' || flrObj.parametersName == '外院预约') {
                if (valueResult.indexOf('互联网预约') > -1) {
                  valueResult.splice(valueResult.indexOf('互联网预约'), 1)
                }
                if (valueResult.indexOf('非互联网预约') > -1) {
                  valueResult.splice(valueResult.indexOf('非互联网预约'), 1)
                }
              }
              // 临床预约来源数据内数据为空的情况，临床预约、联合预约选项不勾选，为了保险起见(老数据问题)，非临床预约也给过滤掉
              if (flrObj.parametersType == 'LCYY' || flrObj.parametersName == '临床预约') {
                if (valueResult.indexOf('非临床预约') > -1) {
                  valueResult.splice(valueResult.indexOf('非临床预约'), 1)
                }
                if (valueResult.indexOf('临床预约') > -1) {
                  valueResult.splice(valueResult.indexOf('临床预约'), 1)
                }
                if (valueResult.indexOf('联合预约') > -1) {
                  valueResult.splice(valueResult.indexOf('联合预约'), 1)
                }
              }
              // 转诊预约来源数据内转诊预约和非转诊预约为空的情况下 转诊预约不勾选，为了保险起见(老数据问题)，非转诊预约也给过滤掉
              if (flrObj.parametersType == 'VIP' || flrObj.parametersName == '转诊预约') {
                if (valueResult.indexOf('非转诊预约') > -1) {
                  valueResult.splice(valueResult.indexOf('非转诊预约'), 1)
                }
                if (valueResult.indexOf('转诊预约') > -1) {
                  valueResult.splice(valueResult.indexOf('转诊预约'), 1)
                }
              }
              // this.channel['newAll'].value = valueResult
            }
          }
          continue
        } else if (flrObj.parametersType === 'YYLY') {
          // 预约来源
          this.channel[flrObj.parametersType].value = flrObj.parametersValues ? flrObj.parametersValues.split(channelSplitKey) : []
          console.log('this.channel=>YYLY', this.channel)
          // debugger
        }
      }
      this.channel['newAll'].value = valueResult // valueResult是给newAll用的
      if (this.formdata.appointmentFilters.length === 0) {
        this.addCondition()
      }
    },

    // 添加场景条件
    addCondition() {
      this.formdata.appointmentFilters.push({
        parametersType: '',
        parametersValues: '',
        parametersName: '',
        conditionControl: '',
        conditionSelectValueOptions: []
      })
    },
    initAppointmentFilters() {
      let arr = []
      arr.push({
        parametersType: '',
        parametersValues: '',
        parametersName: '',
        conditionControl: '',
        conditionSelectValueOptions: []
      })
      this.formdata.appointmentFilters = arr
    },
    // 删除场景条件
    deleteCondition(index) {
      // if (this.formdata.appointmentFilters.length === 1) {
      //   this.$message.warning('当前只有一个条件')
      //   return
      // }
      this.formdata.appointmentFilters.splice(index, 1)
    },
    changeCondition(_item, _index, showParams) {
      // 如果是读数据展示在form上的 不用清空数据；否则每次切换改变的时候 都需要清空数据
      if (!showParams) {
        this.formdata.appointmentFilters[_index].parametersValues = ''
      }
      this.setTimeout01 = setTimeout(() => {
        this.getControlAndValue(_item, _index)
      }, 500)
    },
    async getControlAndValue(_item, _index) {
      console.log('===getControlAndValue===')
      console.log('_item', _item)
      // 找remark 判断控件
      // index 是 _item在规则数据字典中的位置
      let index = this.ruleConditionOptions.findIndex(item => item.dicEname === (_item && _item.parametersType) || '')
      // 规则数据字典存在
      if (index !== -1) {
        this.placeholderKey[_index] = this.ruleConditionOptions[index].dicName
        this.formdata.appointmentFilters[_index].parametersName = this.ruleConditionOptions[index].dicName
        // 存在conditionValue、是字符串、多选择的控件array，需要进行convert '1,2'=>[1,2]
        // 给编辑的时候使用
        if (
          (this.ruleConditionOptions[index].controllType === '3' || this.ruleConditionOptions[index].controllType === '5') &&
          _item.parametersValues &&
          typeof _item.parametersValues === 'string'
        ) {
          this.formdata.appointmentFilters[_index].parametersValues = this.formdata.appointmentFilters[_index].parametersValues.split('、')
        }
        if (
          this.ruleConditionOptions[index].controllType === '1' &&
          _item.parametersValues &&
          typeof _item.parametersValues === 'number'
        ) {
          this.formdata.appointmentFilters[_index].parametersValues = this.formdata.appointmentFilters[_index].parametersValues.toString()
        }
        // 获取相应控件
        this.formdata.appointmentFilters[_index].conditionControl = this.ruleConditionOptions[index].controllType
        // this.formdata.appointmentFilters[_index].modelType = this.ruleConditionOptions[index].modelType
        // 获取相应的方法 来获取控件里面的数值
        // console.log('this.ruleConditionOptions[index].clientMethod', this.ruleConditionOptions[index].clientMethod)
        if (this.ruleConditionOptions[index].clientMethod) {
          // 获取下列方法名字 例如 mx_getDicMethod(getDepArea, params ) 引用混入方法
          let params = {
            HospitalCode: this.hospitalCode,
            Dep: this.dep,
            type: '班次',
            SysAppId: sysAppId // 新增
          }
          if (this.ruleConditionOptions[index].clientMethod == 'getApplyDoctorList') {
            params.type = '申请医生'
            params.Dep = ''
          } else if (this.ruleConditionOptions[index].clientMethod == 'getApplySqdepList') {
            params.type = '申请科室'
            params.Dep = ''
          } else if (this.ruleConditionOptions[index].clientMethod == 'getApplyWardnoList') {
            params.type = '申请病区'
            params.Dep = ''
          }
          const resDicOptions = await this.mx_getDicMethod(this.ruleConditionOptions[index].clientMethod, params)
          this.formdata.appointmentFilters[_index].conditionSelectValueOptions = resDicOptions
          this.$forceUpdate()
        } else {
          // console.log('不存在相应方法')
        }
        console.log('this.formdata.appointmentFilters[_index].conditionControl', this.formdata.appointmentFilters[_index].conditionControl)
      }
    },
    // 获取过滤条件类型getRuleItemDicList
    getRuleItemDicList() {
      // console.log('获取过滤条件类型==getRuleItemDicList==')
      const appSetting = this.appSetting
      // console.log('appSetting', appSetting)
      return new Promise(async resolve => {
        if (this.ruleConditionOptionsFlr.length) {
          resolve()
        } else {
          const params = {
            HospitalCode: this.hospitalCode
          }
          await getItemDicList(params).then(res => {
            // console.log('===getItemDicList===', res)
            if (res && res.code === 10000) {
              let list = res.content.list
              // console.log('appSetting.isUpperBigpart', appSetting.isUpperBigpart)
              if (appSetting.isUpperBigpart) {
                list.forEach(item => { // toUpperCase
                  if (item.dicEname.toLowerCase() === 'bigpart') {
                    item.dicEname = item.dicEname.toUpperCase()
                    // console.log('item.dicEname', item.dicEname)
                  }
                  return item
                })
              } else {
                list.forEach(item => { // toLowerCase
                  if (item.dicEname.toLowerCase() === 'bigpart') {
                    item.dicEname = item.dicEname.toLowerCase()
                    // console.log('item.dicEname', item.dicEname)
                  }
                  return item
                })
              }
              // console.log('==list==', list)
              // console.log('this.$store.state.user.parametersTypeByPartKey1', this.$store.state.user.parametersTypeByPartKey1)
              // console.log('this.$store.state.user.parametersTypeByPartKey2', this.$store.state.user.parametersTypeByPartKey2)
              this.ruleConditionOptions = list.filter(item => item.modelType === 2)
              console.log('==this.ruleConditionOptions==', this.ruleConditionOptions)
              // console.log('==this.ruleConditionOptionsFlr==', this.ruleConditionOptionsFlr)
              // console.log('过滤之前this.ruleConditionOptions', this.ruleConditionOptions)
              this.ruleConditionOptionsFlr = this.ruleConditionOptions.filter(item => {
                return (
                  item.dicEname !== this.$store.state.user.parametersTypeByPartKey2 &&
                  item.dicEname !== this.$store.state.user.parametersTypeByPartKey1 &&
                  item.dicEname !== 'checkDep' &&
                  item.dicEname !== 'VIP' &&
                  item.dicEname !== 'WYYY' &&
                  item.dicEname !== 'LCYY'
                )
              })
              console.log('过滤之后this.ruleConditionOptionsFlr====', this.ruleConditionOptionsFlr)
            }
          })
          resolve()
        }
      })
    },
    // 监听检查部位,全选
    handleCheckAllChangeBigpart(data) {
      console.log('监听检查部位data全选', data)
      if (this.filterTextBigpart) {
        this.bigpartChecked = data ? [...this.bigpartData].map(x => { return x.value }) : []
      } else {
        this.bigpartChecked = data ? [...this.bigpartDataZC].map(x => { return x.value }) : []
      }
      console.log('this.bigpartChecked', this.bigpartChecked)
      this.bigpartIsIndeterminate = false
      this.changeSmallpart()
      // if (this.parametersTypeByPart.toLowerCase() != 'dengjipart') {
      //   this.getSmallpart()
      // }
    },
    // 监听检查项目,全选
    handleCheckAllChangeSmallpart(data) {
      // console.log('监听检查项目data全选', data)
      if (this.filterTextSmallpart) {
        this.smallpartChecked = data ? [...this.smallpartData].map(x => { return x.value }) : []
      } else {
        this.smallpartChecked = data ? [...this.smallpartDataZC].map(x => { return x.value }) : []
      }
      this.smallpartIsIndeterminate = false
    },
    // 监听检查部位,选择
    async handleCheckChangeBigpart(data) {
      // console.log('监听检查部位data选择', data)
      // console.log('bigpartChecked', this.bigpartChecked)
      // console.log('this.parametersTypeByPart.toLowerCase()', this.parametersTypeByPart.toLowerCase())
      // if (this.parametersTypeByPart.toLowerCase() == 'dengjipart') { // dengjipart
      //   // console.log('this.smallPartNodes', this.smallPartNodes)
      //   data.forEach(item => {
      //     // 判断之前的检查部位数据中是否有小部位，若有则过滤
      //     let index = this.smallPartNodes.indexOf(item)
      //     if (index > -1) {
      //       // console.log('过滤之前', this.bigpartChecked)
      //       this.bigpartChecked = this.bigpartChecked.splice(index, 1)
      //       // console.log('过滤之后', this.bigpartChecked)
      //     }
      //   })
      // }
      console.log('this.bigpartChecked', this.bigpartChecked)
      let checkedCount = data.length
      this.bigpartCheckAll = checkedCount === this.bigpartDataZC.length
      this.bigpartIsIndeterminate = checkedCount > 0 && checkedCount < this.bigpartDataZC.length
      // this.getSmallpart()
      if (this.parametersTypeByPart.toLowerCase() != 'dengjipart') {
        await this.getSmallpart()
      }
    },
    // 监听检查项目,选择
    handleCheckChangeSmallpart(data) {
      // console.log('监听检查项目data选择', data)
      let checkedCount = data.length
      this.smallpartCheckAll = checkedCount === this.smallpartDataZC.length
      this.smallpartIsIndeterminate = checkedCount > 0 && checkedCount < this.smallpartDataZC.length
    },
    // 获取 检查部位、检查项目
    async getBigPartGettreeList() {
      // console.log('获取 检查部位、检查项目=>getBigPartGettreeList')
      return new Promise(async resolve => {
        if (this.bigpartData.length !== 0 && (this.treeBigpartloading || this.treeSmallpartloading)) {
          resolve()
          return
        }
        let count = 0
        console.warn('count', count)
        this.getBigPartFlag = true
        const runSend = async () => {
          if (count >= 2) {
            this.treeLoading = false
            this.getBigPartFlag = false
            console.warn('count', count)
            console.log('====calsetrule====')
            // this.$nextTick(() => {
            //   this.calSetRule()
            // }, 500)
            resolve()
            return
          } else if (count === 0) {
            this.treeLoading = true
            this.treeBigpartloading = true
            this.treeSmallpartloading = true
            await this.getBigPart().then(res => {
              count++
              console.warn('count', count)
              runSend()
            })
            await this.getAllSmallpart().then(res => {
              count++
              console.warn('count', count)
              runSend()
              // this.treeLoading = false
              // this.getBigPartFlag = false
              // this.$nextTick(() => {
              //   this.calSetRule()
              // }, 500)
            })
          }
        }
        await runSend()

        // this.treeLoading = true
        // this.treeBigpartloading = true
        // this.treeSmallpartloading = true
        // Promise.all([this.getBigPart(), this.getAllSmallpart()]).then(() => {
        //   this.treeLoading = false
        //   this.getBigPartFlag = false
        //   setTimeout(() => {
        //     console.log('==calsetrule==')
        //     this.calSetRule()
        //   }, 2000)
        // })

        // await this.getBigPart().then(res => {
        //   count++
        //   console.warn('count', count)
        //   // runSend()
        // })
        // await this.getAllSmallpart().then(res => {
        //   count++
        //   console.warn('count', count)
        //   // runSend()
        //   this.treeLoading = false
        //   this.getBigPartFlag = false
        //   this.$nextTick(() => {
        //     this.calSetRule()
        //   }, 500)
        // })
      })
    },
    getBigPart(e) {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCode,
          Dep: this.dep,
          modality: this.modality
        }
        // 当取消设备类型过滤的时候
        if (!e) {
          delete params.modality
        } else {
          params.modality = this.modality
        }
        // console.log('params', params)
        await getBigPartListRoom(params).then(res => {
          this.treeBigpartloading = false
          if (res && res.code === 10000) {
            let partNodes = res.content.list
            let pN = []
            partNodes.forEach((item, index) => {
              const pItem = {
                id: index,
                value: item
              }
              pN.push(pItem)
            })
            this.bigpartDataZC = JSON.parse(JSON.stringify(pN))
            this.bigpartData = JSON.parse(JSON.stringify(this.bigpartDataZC))
            // console.log('this.bigpartData', this.bigpartData)
            this.$refs.virtualList1 && this.$refs.virtualList1.reset()
          }
        })
        resolve()
      })
    },
    // 获取所有的小部位
    getAllSmallpart(e) {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCode,
          Dep: this.dep,
          modality: this.modality,
          Bigpart: '' // this.bigpartCheckAll ? '' : this.bigpartChecked.join(',')
        }
        // 当取消设备类型过滤的时候
        if (!e) {
          delete params.modality
        } else {
          params.modality = this.modality
        }
        // console.log('params', params)
        await getHisCheckroomgetSmallpartlistRoom(params).then(res => {
          this.treeSmallpartloading = false
          if (res && res.code === 10000) {
            let partNodes = res.content.list
            let pN = []
            partNodes.forEach((item, index) => {
              const pItem = {
                id: index,
                value: item
              }
              pN.push(pItem)
            })
            this.smallpartDataZC = JSON.parse(JSON.stringify(pN))
            this.smallpartChecked = this.smallpartChecked.filter(item => this.smallpartDataZC.findIndex(part => part.value === item) >= 0)
            this.smallpartCheckAll = this.smallpartChecked.length > 0 && this.smallpartChecked.length === this.smallpartData.length
            this.smallpartIsIndeterminate = false
            // 小部位排序
            this.smallPartSort(this.smallpartDataZC, this.smallpartChecked, [])
            this.$refs.virtualList2 && this.$refs.virtualList2.reset()
          }
        })
        resolve()
      })
      // return new Promise(async resolve => {
      //   const params = {
      //     HospitalCode: this.hospitalCode,
      //     Dep: this.dep,
      //     Bigpart: ''
      //   }
      //   // console.log('params', params)
      //   await getHisCheckroomgetSmallpartlistRoom(params).then(res => {
      //     this.treeSmallpartloading = false
      //     if (res && res.code === 10000) {
      //       this.smallPartNodes = res.content.list
      //     }
      //   })
      //   resolve()
      // })
    },
    // 待优化
    getSmallpart() {
      return new Promise(async resolve => {
        let currentBigPart = ''
        let bpcLen = this.bigpartChecked.length
        if (bpcLen > 0) {
          currentBigPart = this.bigpartChecked[bpcLen - 1]
        }
        // const deptRoom = getRoomTagCurr()
        // console.log('deptRoom==>getBigPart', deptRoom)
        // const Modality = deptRoom.split('#')[1]
        // const deptRoom = getDefaultRoom()
        // this.modality = deptRoom.length && deptRoom[3].split('-')[2]
        const params = {
          HospitalCode: this.hospitalCode,
          Dep: this.dep,
          Modality: this.modality,
          Bigpart: this.bigpartCheckAll ? '' : currentBigPart
        }
        // console.log('params', params)
        await getHisCheckroomgetSmallpartlistRoom(params).then(res => {
          this.treeSmallpartloading = false
          if (res && res.code === 10000) {
            let partNodes = res.content.list
            let pN = []
            partNodes.forEach((item, index) => {
              const pItem = {
                id: index,
                value: item
              }
              pN.push(pItem)
            })
            let currentData = JSON.parse(JSON.stringify(pN))
            // console.log('currentData', currentData)
            // this.smallpartData = JSON.parse(JSON.stringify(this.smallpartDataZC))
            // console.log('this.smallpartData111', this.smallpartData)
            // console.log('this.smallpartChecked111', this.smallpartChecked)
            // this.smallpartChecked = this.smallpartChecked.filter(item => this.smallpartDataZC.findIndex(part => part.value === item) >= 0)
            this.smallpartCheckAll = this.smallpartChecked.length > 0 && this.smallpartChecked.length === this.smallpartData.length
            this.smallpartIsIndeterminate = false
            // 小部位排序
            // console.log('this.smallpartDataZC全部的数据', this.smallpartDataZC)
            // console.log('this.smallpartChecked', this.smallpartChecked)
            // console.log('currentData', currentData)
            this.smallPartSort(this.smallpartDataZC, this.smallpartChecked, currentData)
          }
        })
        resolve()
      })
    },
    // 小部位排序
    /**
     * @param {Object} allData 所有的小部位数据
     * @param {Object} smallpartChecked 已经选择的小部位数据
     * @param {Object} currentData 当前所选择大部位后所过滤出的小部位数据(大部位的子项)
     */
    smallPartSort(allData, smallpartChecked, currentData) {
      let initData = allData
      let dataResult = []
      // 已选择的
      let data1 = initData.filter(item => smallpartChecked.indexOf(item.value) > -1) // smallpartChecked
      // 当前需排前面的, 未选择中过滤出当前需排前面的
      let data2 = currentData.filter(item => smallpartChecked.indexOf(item.value) == -1)
      // 未选择的
      let data3 = []
      // data2 = currentData // data3.filter(item => currentData.indexOf(item.value) > -1)
      if (currentData.length) {
        let currentDataAndCheckedArr = data2.map(item => item.value).concat(smallpartChecked)
        // console.log('currentDataAndCheckedArr', currentDataAndCheckedArr)
        // 刷新未选择的
        data3 = initData.filter(item => currentDataAndCheckedArr.indexOf(item.value) == -1)
        dataResult = [...data1, ... data2, ... data3]
      } else {
        data3 = initData.filter(item => smallpartChecked.indexOf(item.value) == -1)
        dataResult = [...data1, ... data3]
      }
      this.smallpartData = dataResult
      this.$refs.virtualList2 && this.$refs.virtualList2.reset()
    },
    filterBigpart(val) {
      const d = this.bigpartDataZC.filter(item => item.value && item.value.indexOf(val) >= 0)
      this.bigpartData = d
    },
    filterSmallpart(val) {
      const d = this.smallpartDataZC.filter(item => item.value && item.value.indexOf(val) >= 0)
      this.smallpartData = d
    },
    changeSmallpart(val) {
      // console.log('changeSmallpart')
      // const d = this.smallpartDataZC.filter(item => item.value && item.value.indexOf(val) >= 0)
      // this.smallpartData = d
      // console.log('this.smallpartDataZC', this.smallpartDataZC)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-grid{
  padding-bottom:10px;
  border-bottom: solid 1px #DBDFE9;
  &:last-child{
    border-bottom: none;
  }
  .fg-tit{
    display: flex;
    line-height: 32px;
    .txt{
      flex: 1;
      font-weight: bold;
      .tit_tips{
        font-weight: 500;
        font-size: 12px;
      }
    }
    .flr-add{
      user-select: none;
      color: #00C0EF;
      cursor: pointer;
    }
  }
}
.flr-main{
  .rule-item{
    margin-bottom: 4px;
  }
}
.table-main{
  padding: 8px 10px;
  background-color: #F3F6FB;
  /deep/ .el-table td,/deep/  .el-table th{
    padding: 4px 0;
  }
}
.checkbox_fitem{
  width: 100%;
  /deep/ .el-form-item__content{
    width: 100%;
  }
  .checkbox_box{
    background-color: #fff;
    height: 470px;
    width: 100%;
    overflow: hidden;
    overflow-y: auto;
    /deep/ .el-checkbox{
      width: 100%;
      padding: 2px 4px;
    }
  }
}
.ruleTemp-channel-form{
  /deep/ .el-select {
    width: 126px;
  }
  /deep/ .el-form-item{
    margin-right: 6px;
    font-weight: 500;
    &:last-child{
      margin-right: 0;
    }
  }
  // /deep/ .el-form-item .el-form-item__label {
  //   line-height: 18px;
  // }
}
</style>
